package com.example.config;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ErrorMsg;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: sn
 * @Desc something
 * @Date: 2020/12/16
 */
public class CustomUrlBlockHandler implements UrlBlockHandler {
    public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse response, BlockException e) throws IOException {
        Map msg=new HashMap();
        if(e instanceof FlowException){
            msg.put("message","限流了");
            msg.put("code",100);
        }else if(e instanceof DegradeException){
            msg.put("message","熔断了");
            msg.put("code",100);
        }else{
            msg.put("message","其他异常");
            msg.put("code",100);
        }
        response.setStatus(500);
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type","application/json;charset=utf-8");
        response.setContentType("application/json;charset=utf-8");
        //response.getWriter().write(msg.toString());
        new ObjectMapper().writeValue(response.getWriter(),msg);
    }
}
